﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Operation;
using pinduoduo.Model;
using pinduoduo.Util;
using Sunny.UI;
using Tk.Soc.License.Utils;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo
{
    public partial class Login : UIForm
    {
        Dictionary<string, int> dicErrrorLogin = new Dictionary<string, int>();
        public Login()
        {
            InitializeComponent();
            this.machineCode.Text = HardwareInfoHelper.GetWinHardwareInfoCode();
            G_Api.MACHINECODE = this.machineCode.Text;
            string userName="";
            string password = "";
            SystemUtil.ReadLoginUser(ref userName, ref password);
            this.userName.Text = userName;
            this.password.Text = password;
        }

        private async void uiButton3_Click(object sender, EventArgs e)
        {
            string userName = this.userName.Text.Trim();
            string password = this.password.Text.Trim();
            string machineCode = this.machineCode.Text.Trim();

            string msg;
            bool isLocking = SystemUtil.IsLocking(out msg);
            if (isLocking)
            {
                this.msg.Text = msg;
                //TipMsg = msg;
                return;
            }

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)) 
            {
                this.msg.Text = "用户名或密码不能为空";
                //MessageBox.Show("用户名或密码不能为空");
                return;
            }
            var response = await G_Api.Login(userName, password, machineCode,"pdd");
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(response.Content);

                if (jo["code"].ToString() == "200")
                {
                    if (dicErrrorLogin.ContainsKey(userName))
                        dicErrrorLogin[userName] = 0;

                    G_Api.TOKEN = jo["token"].ToString();
                    var vipUser = await G_Api.GetVipUser();
                    var softwareExpire = await G_Api.SoftwareExpire();

                    if (!softwareExpire)
                    {
                        MessageBox.Show("您的软件到期，请充值！");
                        return;
                    }
                    SystemUtil.RememberLoginUser(userName, password);
                    this.Hide();
                    new Main().Show();
                    //new MainWindows().Show();
                }
                else if (jo["code"].ToString() == "250") 
                {
                    MessageBox.Show(jo["msg"].ToString());
                }
                else if (jo["code"].ToString() == "251")
                {
                    MessageBox.Show(jo["msg"].ToString());
                }
                else
                {
                    if (dicErrrorLogin.ContainsKey(userName))
                    {
                        this.msg.Text = $"账号或密码错误 {dicErrrorLogin[userName]} 次，连续错误5次将被锁定5分钟";
                    }
                    else 
                    {
                        this.msg.Text = $"账号或密码错误，连续错误5次将被锁定5分钟";
                    }

                }

                if (!dicErrrorLogin.ContainsKey(userName))
                    dicErrrorLogin.Add(userName, 1);
                else
                    dicErrrorLogin[userName]++;
                 
                if (dicErrrorLogin[userName] >= 5)
                {
                    SystemUtil.LockSystem();
                    dicErrrorLogin[userName] = 0;
                    //var detail = string.Format("用户【{0}】在【{1}】被锁定",
                    //    userName,
                    //    DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                    //this.msg.Text=detail;
                }
            }
            else 
            {
                MessageBox.Show("连接服务器失败");
            }


        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            new RegisterUser().Show();
        }

        private async void Login_Load(object sender, EventArgs e)
        {
            await G_Api.GetMyIp();
        }

        private void uiRichTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private async  void uiTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.uiTabControl1.SelectedTab.Text == "注册")
            {
                this.MACHINE_CODE = G_Api.MACHINECODE;
                await CaptchaImage();
            }
               
        }

        private string uuid;
        private string MACHINE_CODE;

        private async void  uiButton4_Click(object sender, EventArgs e)
        {
            string userName = this.RegUserName.Text.Trim();
            string password = this.RegPassword.Text.Trim();
            string code = this.code.Text;
            this.RegMsg.Text = "";
            if (userName.Length < 5 || userName.Length > 10)
            {
                this.RegMsg.Text = "用户名长度在5-10位";
                return;
            }

            if (password.Length < 5 || password.Length > 10)
            {
                this.RegMsg.Text = "密码长度在5-10位";
                return;
            }

            if (string.IsNullOrWhiteSpace(code))
            {
                this.RegMsg.Text = "验证码不能为空";
                return;
            }
            ApiUser apiUser = new ApiUser();
            apiUser.code = code;
            apiUser.uuid = uuid;
            apiUser.userName = userName;
            apiUser.nickName = userName;
            apiUser.password = password;
            var res = await G_Api.RegisterUser(apiUser, MACHINE_CODE, code, uuid);
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(res.Content);

                if (jo["code"].ToString() == "200")
                {
                    this.RegMsg.Text = "注册成功";
                }
                else
                {
                    this.RegMsg.Text = jo["msg"].ToString();
                }
            }
            else
            {
                this.RegMsg.Text = "注册异常";
            }
            await CaptchaImage();
        }



        private async Task CaptchaImage()
        {
            var response = await G_Api.CaptchaImage();
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(response.Content);

                if (jo["code"].ToString() == "200")
                {
                    uuid = jo["uuid"].ToString();
                    if (!string.IsNullOrWhiteSpace(jo["img"].ToString()))
                    {
                        byte[] bytes = Convert.FromBase64String(jo["img"].ToString());
                        MemoryStream s = new MemoryStream(bytes, true);
                        s.Write(bytes, 0, bytes.Length);

                        Image a = new Bitmap(s);

                        Bitmap bit = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
                        Graphics g = Graphics.FromImage(bit);//从指定的 Image 创建新的 Graphics(绘图)。
                        g.DrawImage(a, new Rectangle(0, 0, bit.Width, bit.Height), new Rectangle(0, 0, a.Width, a.Height), GraphicsUnit.Pixel);
                        this.pictureBox1.Image = bit;
                    }
                }
                else
                {
                    this.msg.Text = "获取验证码失败";
                }
            }
        }

        private async void pictureBox1_Click(object sender, EventArgs e)
        {
            await CaptchaImage();
        }

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.RechargeUserName.Text)) 
            {
                RechargeMsg.Text = "请输入充值账号";
            }

            if (string.IsNullOrWhiteSpace(this.Card.Text))
            {
                RechargeMsg.Text = "请输入卡密";
            }

           var res = await G_Api.Recharge(this.RechargeUserName.Text, this.Card.Text);
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(res.Content);
                if (jo["code"].ToString() == "200") 
                {
                    this.RechargeMsg.Text = "充值成功";
                }
                else
                {
                    this.RechargeMsg.Text = jo["msg"].ToString();
                }
            }
        }

        private void uiButton2_Click_1(object sender, EventArgs e)
        {
            AutoUpdate.GetInstance().updater.BeginCheckUpdateInProcess();

        }

        private void uiButton2_Click_2(object sender, EventArgs e)
        {
            //调用系统默认的浏览器
            System.Diagnostics.Process.Start("http://www.pdd88.top");
        }
    }
}
